import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
import pandas
from tkModelFrame.commonmodels import *


class SearchFrame(tk.Frame):
    def __init__(self, root, cindex):
        super(SearchFrame,self).__init__(root)
        self.searchmumber = None
        self.searchentry = ttk.Entry(self)
        self.target = [-1,-1]
        self.cindex = cindex
        self.columnbox = DynamicDropMenu(self, defaultstr="", menulist=cindex,
                                         buttonlabel="搜索", command=self.gettarget,width=14)
        self.resultv = tk.StringVar(self)
        self.resultv.set("无")
        self.cbv = tk.StringVar(self)
        self.typebox = ttk.Combobox(self, textvariable=self.cbv, width=8, state="readonly")
        self.typebox["value"] = ['文本','数值']
        self.searchresult = tk.StringVar(self)

        tk.Label(self, text="搜索数据:").grid(row=0, column=0, padx=2)
        self.searchentry.grid(row=0, column=1, padx=2)
        tk.Label(self, text="数据类型:").grid(row=0, column=2, padx=2)
        self.typebox.grid(row=0, column=3, padx=2)
        tk.Label(self, text="列位置:").grid(row=0, column=4, padx=2)
        self.columnbox.grid(row=0, column=5, padx=2)

    def reset_columnbox(self, cindex: list):
        self.cindex = cindex
        self.columnbox.resetmenu("", self.cindex)

    def showresult(self, result = (0, 0)):
        if result[1] != 0:
            self.searchresult.set(f"{result[0]}/{result[1]}")
        else:
            self.searchresult.set("未找到数据")

    def resetcmd(self,command):
        if callable(command):
            self.columnbox.checkbutton.configure(command=command)

    def gettarget(self):
        targettype = self.typebox.get()
        column= self.columnbox.getvalue()
        target = self.searchentry.get()
        if column != "" and targettype != "" and target !="":
            if targettype == '数值':
                try:
                    target = float(target)
                except:
                    tk.messagebox.showinfo("类型错误警告", "数据类型错误，请输入数值！")
                    self.focus_force()
            elif targettype == '文本':
                target = target
            # print(f"在\"{column}\"列(第{self.cindex.index(column)}列)搜索格式为{targettype}，值为\"{target}\"的变量")
            return [column, target]
        else:
            print("请输入数据")
            return "无输入"


class DataFrameViewr(tk.Frame):
    def __init__(self, root, name = "DataFrame预览器", maxheight = 4095, df = pandas.DataFrame(), minwidth = 200):
        super(DataFrameViewr,self).__init__(root)
        self.root = root
        self.name= name
        self.df=df
        self.maxheight = maxheight
        self.cindex = self.df.columns.values.tolist()
        tk.Label(self, text=name, font=('宋体',15), pady= 10).pack()
        self.searchframe = SearchFrame(self,cindex=self.cindex)
        self.searchframe.pack()
        self.table = DataTable(self,rindex=self.df.index.values.tolist(), minwidth=minwidth,
                               cindex=self.cindex,values=self.df.values.tolist(),maxheight=self.maxheight
                               )
        self.resultlist = []
        self.resultlistpointer = 0
        self.table.pack()
        self.searchframe.resetcmd(self.searchButtonCallback)

    def searchButtonCallback(self):
        target = self.searchframe.gettarget()
        if type(target) is not str:
            if target[0] != self.searchframe.target[0] or target[1] != self.searchframe.target[1]:
                print("这是一个新数据")
                self.search(target)
                self.resultlistpointer = 0
            else:
                print("之前找到过了")
                self.resultlistpointer+=1
                if self.resultlistpointer >= len(self.resultlist):
                    self.resultlistpointer = 0
            if len(self.resultlist) >0 :
                self.table.movefocus([self.resultlist[self.resultlistpointer],self.cindex.index(target[0])])

    def search(self, target: list):
        resultlist = self.df[self.df[target[0]]==target[1]].index.values.tolist()
        if len(resultlist) >0 :
            print(f"在\"{target[0]}\"列(第{self.cindex.index(target[0])}列)找到数据{target[1]}")
            self.resultlist = resultlist[:]
            self.searchframe.target = target[:]
            return True
        else:
            tk.messagebox.showinfo("查询警告",
                                   f"在\"{target[0]}\"列(第{self.cindex.index(target[0])}列)没有找到数据\"{target[1]}\"")
            self.focus_force()
            return False

    def loaddata(self, df):
        if df.__class__ == pandas.DataFrame:
            print("载入新的表格数据")
            self.df = pandas.DataFrame(data=df, columns=df.columns.values.tolist())
            self.refreshtable()
    def refreshtable(self):
        self.table.destroy()
        self.cindex = self.df.columns.values.tolist()
        self.table = DataTable(self,rindex=self.df.index.values.tolist(),
                               cindex=self.cindex,values=self.df.values.tolist(),maxheight=self.maxheight
                               )
        self.searchframe.reset_columnbox(cindex=self.cindex)
        self.resultlist = []
        self.resultlistpointer = 0
        self.table.pack()


if __name__ == "__main__":
    # master = tk.Tk()
    # # tk.Label(master, text = "测试").pack()
    # # tvsta = False
    # # TV = SubWindow(root=master, title="弹出窗口测试")
    # # tk.Button(master, text="弹出窗口", command=TV.open).pack()
    # # newlist = [0,1,2,3]
    # import json
    #
    # master.geometry("600x400")
    #
    # with open("AgentListValues.json", "r") as f:
    #     agentlistvalues = json.load(f)
    #     f.close()
    #
    # with open("AgentListCindex.json", "r") as f:
    #     cindex = json.load(f)
    #     f.close()
    # # e = tk.Entry(master,width=10)
    # # e.pack()
    #
    # # def gettarget():
    # #     target = e.get().split(',')
    # #     target[0] = int(target[0])
    # #     target[1] = int(target[1])
    # #     print(mt.movefocus(target))
    #
    # # def searchintable(target = [0,0], height = 4095):
    # #     if target[1] <= height:
    # #         target[0] = str(hex(int(target[0])+1)).upper()[2:]
    # #         target[0] = 'I000'[0:4-len(target[0])]+target[0]
    # #         mt.table.see(target[0])
    # #         mt.table.selection_set(target[0])
    # #         mt.table.xview(200*(target[1]-1)-100)
    # #     else:
    # #         print("超出大小")
    #
    # df = pandas.DataFrame(columns=cindex, data=agentlistvalues)
    # print(df)
    #
    # # tk.ttk.Button(master, text="按行序号索引", command=gettarget).pack()
    # # mt = DataTable(master, list(range(len(agentlistvalues))), cindex, agentlistvalues, maxheight=100)
    # # mt.pack()
    # #
    # # mt.movefocus([400,3])
    # dfv = DataFrameViewr(master, df = df)
    # dfv.pack()
    # master.mainloop()
    pass

